package com.lekang.le.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import java.util.Map;

import com.lekang.common.core.domain.entity.SysRole;
import com.lekang.common.core.domain.entity.SysUser;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.le.domain.PendingTasks;
import com.lekang.le.service.IPendingTasksService;
import com.lekang.system.domain.SysUserRole;
import com.lekang.system.mapper.SysRoleMapper;
import com.lekang.system.mapper.SysUserMapper;
import com.lekang.system.mapper.SysUserRoleMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.le.mapper.AccraditationRecordMapper;
import com.lekang.le.domain.AccraditationRecord;
import com.lekang.le.service.IAccraditationRecordService;

/**
 * 审批记录Service业务层处理
 * 
 * @author szh
 * @date 2025-10-20
 */
@Service
public class AccraditationRecordServiceImpl implements IAccraditationRecordService 
{
    @Autowired
    private AccraditationRecordMapper accraditationRecordMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private IAccraditationRecordService accraditationRecordService;
    @Autowired
    private IPendingTasksService pendingTasksService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询审批记录
     * 
     * @param id 审批记录主键
     * @return 审批记录
     */
    @Override
    public AccraditationRecord selectAccraditationRecordById(Long id) {
        return accraditationRecordMapper.selectAccraditationRecordById(id);
    }
    @Override
    public AccraditationRecord selectAccraditationRecordByBussniessIdSZH(Long bussniessId) {
        return accraditationRecordMapper.selectAccraditationRecordByBussniessIdSZH(bussniessId);
    }

    /**
     * 查询审批记录列表
     * 
     * @param accraditationRecord 审批记录
     * @return 审批记录
     */
    @Override
    public List<AccraditationRecord> selectAccraditationRecordList(AccraditationRecord accraditationRecord)
    {
        List<AccraditationRecord> accraditationRecords = accraditationRecordMapper.selectAccraditationRecordList(accraditationRecord);
        if(accraditationRecords.size()>0){
            for(AccraditationRecord aa : accraditationRecords){
                System.out.println("aa:::::"+aa);
            }
        }
        return accraditationRecordMapper.selectAccraditationRecordList(accraditationRecord);
    }

    /**
     * 新增审批记录
     *
     * @param accraditationRecord 审批记录
     * @return 结果
     */
    @Override
    public int insertAccraditationRecord(AccraditationRecord accraditationRecord)
    {
        accraditationRecord.setCreateTime(DateUtils.getNowDate());
        return accraditationRecordMapper.insertAccraditationRecord(accraditationRecord);
    }
    @Override
    public int insertAccraditationRecordSZH(AccraditationRecord accraditationRecord)
    {
        accraditationRecord.setCreateTime(DateUtils.getNowDate());
        return accraditationRecordMapper.insertAccraditationRecordSZH(accraditationRecord);
    }

    /**
     * 退住新增审批记录
     *
     * @param accraditationRecord 审批记录
     * @return 结果
     */
    @Override
    public int tuizhuinsertAccraditationRecord(AccraditationRecord accraditationRecord)
    {
        System.out.println("accraditationRecord::::::::::"+accraditationRecord);
        Map<Long, StepConfig> STEP_CONFIG = new HashMap<>();


        // 步骤2：护理主任审批
        STEP_CONFIG.put(2L, new StepConfig("护理员组长", 101L, "审批-护理主任审批", "处理-法务部上传文件", 0L, "法务部员工", 104L));

        // 步骤3：法务部员工上传文件
        STEP_CONFIG.put(3L, new StepConfig("法务部员工", 104L, "处理-法务部上传文件", "审批-副部长退住审批", 1L, "副院长", 102L));


        // 步骤4：副院长退住审批
        STEP_CONFIG.put(4L, new StepConfig("副院长", 102L, "审批-副部长退住审批", "流程结束", 1L, null, null));

 /*
         // 步骤4：结算员调整账单
        STEP_CONFIG.put(4L, new StepConfig("结算员", 105L, "处理-结算员调整账单", "审批-结算组部长审批", 1L, "结算组部长", 106L));

        // 步骤5：结算组部长审批账单
        STEP_CONFIG.put(5L, new StepConfig("结算组部长", 106L, "审批-结算组部长审批", "审批-副部长退住审批", 0L, "副院长", 102L));

        // 步骤6：副部长退住审批
        STEP_CONFIG.put(6L, new StepConfig("副院长", 102L, "审批-副部长退住审批", "处理-结算员费用清算", 0L, "结算员", 105L));

        // 步骤7：结算员费用清算（最后一步）
        STEP_CONFIG.put(7L, new StepConfig("结算员", 105L, "处理-结算员费用清算", "流程结束", 1L, null, null));
*/

        // 审批 -- 拒绝 同意
        // 1.处理数据
        Long stepNo = accraditationRecord.getStepNo();//当前审核步骤
        System.out.println("stepNo:::::::::"+stepNo);
        accraditationRecord.setCreateTime(DateUtils.getNowDate());
        Long ptid = accraditationRecord.getHandleType();//待办任务id
        String taskId = accraditationRecord.getExtraField1();//任务ID ,用于结束结点
        Long busId = accraditationRecord.getBussniessId();//业务id，用于标识.processInstanceBusinessKey(taskId)
        accraditationRecord.setCreateTime(DateUtils.getNowDate());
        //2、向数据库中插入一条数据
        AccraditationRecord record = new AccraditationRecord();

        record.setOpinion(accraditationRecord.getOpinion());
        record.setType(accraditationRecord.getType());
        record.setFinishTime(new Date());
        record.setApproverId(accraditationRecord.getApproverId());
        SysUser currentUser = sysUserMapper.selectUserById(record.getApproverId());
        SysUserRole sysUserRole = sysUserRoleMapper.selectByUserIdSysUserRole(currentUser.getUserId());
        System.out.println("sysUserRole:::::::"+sysUserRole);
        SysRole currentUserRole = sysRoleMapper.selectRoleById(sysUserRole.getRoleId());
        record.setApproverName(currentUser.getNickName());
        record.setApproverNameRole(currentUserRole.getRoleName());  // 需要你们自己查询
        SysRole nextUserRole = new SysRole();
        System.out.println("下一个审批人的角色：：：：：：：："+STEP_CONFIG.get(stepNo).getNextRoleName());
        nextUserRole.setRoleName(STEP_CONFIG.get(stepNo).getNextRoleName());
        List<SysRole> sysRoles = sysRoleMapper.selectRoleList(nextUserRole);
        Long roleId = 0L;
        if(sysRoles.size()>0){
            roleId = sysRoles.get(0).getRoleId();//下一级审核人角色
        }
        System.out.println("下一级审核人角色::::::::::::"+roleId);
        SysUser sysUser = new SysUser();
        System.out.println("currentUser"+currentUser);
        sysUser.setDeptId(200L);
        sysUser.setRoleId(roleId);
        SysUser nextUser = sysUserMapper.selectUserByUserRoleAndDept(sysUser);//下一级审核人
        System.out.println("下一级审核人：：：：：：：：：："+nextUser);
        if(nextUser!=null){
        record.setNextApproverId(nextUser.getUserId());
        record.setNextApprover(nextUser.getNickName());}
        record.setNextApproverRole(STEP_CONFIG.get(stepNo).getNextRoleName());
        record.setBussniessId(busId);
        record.setCurrentStep(STEP_CONFIG.get(stepNo).getStepName());
        record.setNextStep(STEP_CONFIG.get(stepNo).getNextStepName());
        record.setAuditStatus(accraditationRecord.getAuditStatus());
        record.setStepNo(stepNo);  //未知审核步骤是什么
        record.setCreateBy(accraditationRecord.getCreateBy());
        record.setHandleType(1L);
        record.setExtraField2(accraditationRecord.getExtraField2());
        int i =accraditationRecordMapper.insertAccraditationRecord(record);
        //3、根据taskId结束节点
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(busId.toString())
                .processDefinitionKey("tuizhu")
                .taskAssignee(accraditationRecord.getApproverId().toString()).singleResult();
        if(task!=null){
            taskService.complete(task.getId());
        }
        // 4.修改原来的我的待办中的状态和步骤 -- 已处理、3
        PendingTasks pendingTasks = pendingTasksService.selectPendingTasksById(ptid);
        pendingTasks.setStatus(2L);
        pendingTasks.setIsHandle(1L);
        pendingTasks.setStepNo(stepNo+1);
        pendingTasksService.updatePendingTasks(pendingTasks);
        //5、修改该工作流的所有待办步骤为 3
        PendingTasks pendingTasks1 = new PendingTasks();
        pendingTasks1.setBussniessId(busId);
        List<PendingTasks> pendingTasks2 = pendingTasksService.selectPendingTasksList(pendingTasks1);
        for(PendingTasks p2 : pendingTasks2){
            p2.setStepNo(stepNo+1);
            pendingTasksService.updatePendingTasks(p2);
        }
//        System.out.println("审批后下一步得busId:::::::"+busId);
//        System.out.println("下一个任务的执行人：：：：：：：："+nextUser.getUserId());
        // 6、保存下一个人的待办（仅当存在下一个任务时）
        Task nextTask = null;
        if(nextUser!=null){
         nextTask = taskService.createTaskQuery()
                .processInstanceBusinessKey(busId.toString())
                .processDefinitionKey("tuizhu")
                .taskAssignee(nextUser.getUserId().toString()).singleResult();
        }

        // 只有当 nextTask 不为 null 时，才创建下一个待办
        if (nextTask != null) {
            PendingTasks pt = new PendingTasks();
            pt.setBussniessId(busId);
            pt.setTaskId(nextTask.getId()); // 此时 nextTask 非空，可安全调用 getId()
            pt.setTitle(accraditationRecord.getExtraField2()+"的退住申请");
            pt.setType(accraditationRecord.getType());
            pt.setAssignee(record.getNextApprover());
            pt.setAssigneeId(record.getNextApproverId());
            pt.setStatus(1L);
            pt.setApplicationTime(accraditationRecord.getCreateTime());
            Long applicatId = Long.parseLong(accraditationRecord.getCreateBy());
            SysUser sysUser1 = sysUserMapper.selectUserById(applicatId);
            pt.setApplicat(sysUser1.getNickName());
            pt.setApplicatId(applicatId);
            pt.setIsHandle(0L);
            pt.setStepNo(stepNo+1);
            pt.setExtraField2(accraditationRecord.getExtraField2());
            pendingTasksService.insertPendingTasks(pt);
        } else {

            // 可选：流程结束时的处理逻辑，例如打印日志
            System.out.println("流程已结束，无下一个待办任务。业务ID：" + busId);
        }
        return i;
    }

    /**
     * 修改审批记录
     * 
     * @param accraditationRecord 审批记录
     * @return 结果
     */
    @Override
    public int updateAccraditationRecord(AccraditationRecord accraditationRecord)
    {
        accraditationRecord.setUpdateTime(DateUtils.getNowDate());
        return accraditationRecordMapper.updateAccraditationRecord(accraditationRecord);
    }

    /**
     * 批量删除审批记录
     * 
     * @param ids 需要删除的审批记录主键
     * @return 结果
     */
    @Override
    public int deleteAccraditationRecordByIds(Long[] ids)
    {
        return accraditationRecordMapper.deleteAccraditationRecordByIds(ids);
    }

    /**
     * 删除审批记录信息
     * 
     * @param id 审批记录主键
     * @return 结果
     */
    @Override
    public int deleteAccraditationRecordById(Long id)
    {
        return accraditationRecordMapper.deleteAccraditationRecordById(id);
    }

    private static class StepConfig
    {
        private String roleName;
        private Long roleId;
        private String stepName;
        private String nextStepName;
        private Long handleType;
        private String nextRoleName;
        private Long nextRoleId;

        public StepConfig(String roleName, Long roleId, String stepName, String nextStepName,
                          Long handleType, String nextRoleName, Long nextRoleId) {
            this.roleName = roleName;
            this.roleId = roleId;
            this.stepName = stepName;
            this.nextStepName = nextStepName;
            this.handleType = handleType;
            this.nextRoleName = nextRoleName;
            this.nextRoleId = nextRoleId;
        }

        public String getRoleName() { return roleName; }
        public Long getRoleId() { return roleId; }
        public String getStepName() { return stepName; }
        public String getNextStepName() { return nextStepName; }
        public Long getHandleType() { return handleType; }
        public String getNextRoleName() { return nextRoleName; }
        public Long getNextRoleId() { return nextRoleId; }
    }
}
